<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactTrack\Action\Workbench;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactFollow\Contract\ContactFollowContract;
use MoChat\Plugin\ContactTodo\Contract\ContactTodoContract;
use MoChat\Plugin\ContactTrack\Constants\Event;
use MoChat\Plugin\ContactTrack\Contract\ContactTrackContract;

/**
 * 互动轨迹.
 *
 * Class Index
 * @Controller
 */
class Index extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * 互动轨迹表.
     * @Inject
     * @var ContactTrackContract
     */
    private $track;

    /**
     * @Inject
     * @var ContactFollowContract
     */
    private $contactFollowService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    private $workEmployeeService;

    /**
     * @Inject
     * @var ContactTodoContract
     */
    private $contactTodoService;

    /**
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @RequestMapping(path="/workbench/contactTrack/index", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $params['corpId'] = $user['corpId'];
        $params['employeeId'] = $user['id'];
        $params['userId'] = $user['logUserId'];
        // 接收参数
        $params['contactId'] = $this->request->input('contactId');
        $params['event'] = (int) $this->request->input('event', 0);
        $page = $this->request->input('page', 1);
        $perPage = $this->request->input('perPage', 10);
        // 校验参数
        $this->validated($params);
        $where['contact_id'] = (int) $params['contactId'];
        if ($params['event'] > 0) {
            $where['event'] = $params['event'];
        }
        $options = [
            'page' => $page,
            'perPage ' => $perPage,
            'orderByRaw' => 'id desc',
        ];
        $columns = [
            'id',
            'event',
            'content',
            'created_at',
        ];
        $res = $this->track->getContactTrackList($where, $columns, $options);
        // 组织响应数据
        $data = [
            'page' => [
                'perPage' => $perPage,
                'total' => 0,
                'totalPage' => 0,
            ],
            'list' => [],
        ];
        if (empty($res['data'])) {
            return $data;
        }
        // 处理分页数据
        $data['page']['total'] = $res['total'];
        $data['page']['totalPage'] = $res['last_page'];
        // 数据处理
        foreach ($res['data'] as $key => $val) {
            // 跟进记录处理
            if ($val['event'] === Event::FOLLOW || $val['event'] === Event::FOLLOW_TEMPLATE) {
                try {
                    if (strpos($val['content'], '{') === 0) {
                        $content = Json::decode($val['content']);
                    } else {
                        $content = [
                            'title' => '',
                            'content' => $val['content'],
                        ];
                    }
                } catch (\Throwable $e) {
                    continue;
                }

                if (! empty($content)) {
                    $follow = $this->contactFollowService->getContactFollowById($content['target_id'], ['employee_id']);
                    if (! empty($follow)) {
                        $employee = $this->workEmployeeService->getWorkEmployeeById($follow['employeeId'], ['name']);
                        if (! empty($employee)) {
                            $res['data'][$key]['createName'] = $employee['name'];
                        }
                    } else {
                        $res['data'][$key]['createName'] = '';
                    }
                }
            }
            // 待办记录处理
            if ($val['event'] === Event::TODO) {
                try {
                    $content = Json::decode($val['content']);
                } catch (\Throwable $e) {
                    $content = [];
                }

                if (! empty($content)) {
                    $todo = $this->contactTodoService->getContactTodoById($content['target_id'], ['employee_id', 'day', 'time']);
                    if (! empty($todo)) {
                        $employee = $this->workEmployeeService->getWorkEmployeeById($todo['employeeId'], ['name']);
                        if (! empty($employee)) {
                            $res['data'][$key]['createName'] = $employee['name'];
                            $res['data'][$key]['todoTime'] = $todo['day'] . ' ' . $todo['time'];
                        }
                    }
                }
            }
        }
        // 数据处理
        $list = [];
        foreach ($res['data'] as $k => $v) {
            $day = substr($v['createdAt'], 0, 10);
            $list[$day]['week'] = $this->getWeek($day);
            $list[$day]['day'] = $day;
            $v['isNew'] = ! str_contains($v['content'], 'title') ? 0 : 1;
            $v['createdAt'] = date('H:i', strtotime($v['createdAt']));
            $list[$day]['track'][] = $v;
        }
        $data['list'] = array_values($list);
        return $data;
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'contactId' => 'required|integer|min:1|bail',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'contactId.required' => '客户id必传',
        ];
    }

    protected function getWeek($date)
    {
        // 强制转换日期格式
        $date_str = date('Y-m-d', strtotime($date));

        // 封装成数组
        $arr = explode('-', $date_str);

        // 参数赋值
        // 年
        $year = $arr[0];

        // 月，输出2位整型，不够2位右对齐
        $month = sprintf('%02d', $arr[1]);

        // 日，输出2位整型，不够2位右对齐
        $day = sprintf('%02d', $arr[2]);

        // 时分秒默认赋值为0；
        $hour = $minute = $second = 0;

        // 转换成时间戳
        $strap = mktime($hour, $minute, $second, (int) $month, (int) $day, (int) $year);

        // 获取数字型星期几
        $number_wk = date('w', $strap);

        // 自定义星期数组
        $weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];

        // 获取数字对应的星期
        return $weekArr[$number_wk];
    }
}
